﻿//订单模板打印按钮
function Exporttemplate() {
    
    debugger;
    //区域
    var quyu = Xrm.Page.getAttribute("new_quyu").getValue();
    //签约公司
    var qianyuegongsi = Xrm.Page.getAttribute("new_qianyuegongsi").getValue();
    //收款方式
    var paymenttermscode = Xrm.Page.getAttribute("paymenttermscode").getValue();

    var result = GetOrderInfo(qianyuegongsi, paymenttermscode);
    if (result != null) {
        var documenttemplateid= result[0].attributes["documenttemplateid"].value;
        var name = result[0].attributes["name"].value;
        // * @param entitytypecode: the type code of the entity. In the ribbon workbench set a
        //* CRM parameter with value PrimaryEntityTypeCode. ex: 1063
        var entitycode = "1088";
        //模板ID
        var templateid = "9D6916E4-2052-4E03-A0E3-D15A5B133A9A";
        var templatetype = "9940";
        //下载文件名称
        var filename = "客户摘要";
        var entityid = Xrm.Page.data.entity.getId();
        DownloadTemplate(entitycode, documenttemplateid, entityid, templatetype, name, name);
    } else {
        alert("未找到符合条件的订单模板，请联系管理员!");
    }

   
}


function TemplateBtnControl() {
    ////已审核	100000004
    //生效	100000001
    //已完成	100000005
    var status = false;
    var new_status = Xrm.Page.getAttribute("new_status").getValue();
    if (new_status == "100000004" || new_status == "100000001" || new_status == "100000005") {
        status = true;
        return;
    } else {
        status = false;
        return;
    }
    return status;
}




//下载模板
function DownloadTemplate(entitytypecodeint, wordtemplateid, ids, templatetype, fieldforfilename, filenameoverride) {
    Xrm.Page.ui.clearFormNotification("worderror");
    var funcpath = Xrm.Page.context.getClientUrl() + "/_grid/print/print_data.aspx";
    if (typeof ids !== "object") {
        var tids = ids;
        ids = new Array();
        ids.push(tids);
    }
    var wordTemplateId = wordtemplateid;//"f1f7b994-543b-e711-8106-c4346bac2908" test data;
    var currentEntityTypeCode = entitytypecodeint;//"10063" test data;
    var templateType = (templatetype || 9940); //9940 is global and 9941 is personal
    var fieldForFileName = (fieldforfilename || "");
    var formdata = "exportType=MergeWordTemplate&selectedRecords=" + encodeURIComponent(JSON.stringify(ids)) +
        "&associatedentitytypecode=" + currentEntityTypeCode + "&TemplateId=" + wordTemplateId + "&TemplateType=" + templateType;
    var req = new XMLHttpRequest();
   
    req.open("POST", funcpath, true);
    req.responseType = "arraybuffer";
    req.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
    req.setRequestHeader("Accept-Language", "en-US,en;q=0.8");
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.onreadystatechange = function () {
        if (this.readyState == 4) {/* complete */
            req.onreadystatechange = null;
            if (this.status >= 200 && this.status <= 299) {//200 range okay
                var mimetype = (2 === 2) ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                var blob = new Blob([req.response], { type: mimetype });
                var fileNameTemplate = req.getResponseHeader('content-disposition').split('filename=')[1].replace(/'/g, "");
                var dloadurl = URL.createObjectURL(blob);
                var filename = (fieldForFileName !== "" && Xrm.Page.getAttribute(fieldForFileName) !== null && Xrm.Page.getAttribute(fieldForFileName).getValue() !== "") ?
                    Xrm.Page.getAttribute(fieldForFileName).getValue() : fileNameTemplate;
                filename = filenameoverride || filename;
                //new code, prevent IE errors
                if (navigator.msSaveOrOpenBlob) {
                    navigator.msSaveOrOpenBlob(blob, filename + ".docx");
                    return;
                }
                else if (window.navigator.msSaveBlob) { // for IE browser
                    window.navigator.msSaveBlob(blob, filename +".docx");
                    return;
                }
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                debugger;
                a.href = dloadurl;
                a.download = filename+".docx";
                a.click();
                URL.revokeObjectURL(dloadurl);
                //window.location = dloadurl;//we can use just this instead of creating an anchor but we don't get to the name the file
            }
            else {
                Xrm.Page.ui.setFormNotification("An Error occurred generating the word document, please contact support if the issue persists,code: " + this.status, "ERROR", "worderror");
            }
        }
    };
    req.send(formdata);

}



function GetOrderInfo( qianyuegongsi, paymenttermscode) {
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
        "<entity name ='new_salesordertemplate'>" +
        "    <attribute name='new_salesordertemplateid'/>" +
        "    <attribute name='new_uploadname'/>" +
        "    <order attribute='createdon' descending='true'/>" +
        "    <filter type='and'>" +
        "        <condition attribute='new_signingcommpany' operator='eq' value='" + qianyuegongsi+"'/>" +
        "        <condition attribute='new_paymenttermscode' operator='eq' value='" + paymenttermscode+"'/>" +
        "        <condition attribute='statecode' operator='eq' value='0'/>" +
        "        <condition attribute='statuscode' operator='eq' value='1'/>" +
        "    </filter>" +
        " </entity>" +
        " </fetch> ";

    var retrTotalQuota = XrmServiceToolkit.Soap.Fetch(fetchXml);

    if (retrTotalQuota && retrTotalQuota.length > 0) {
        if (retrTotalQuota[0].attributes["new_uploadname"].value) {
            var fetchXmltemplate = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                " <entity name='documenttemplate'>" +
                "   <attribute name='documenttemplateid'/>" +
                "   <attribute name='name'/>" +
                "   <order attribute='modifiedon' descending='false'/>" +
                "   <filter type='and'>" +
                "     <condition attribute='name' operator='like' value='%"+retrTotalQuota[0].attributes["new_uploadname"].value+"%'/>" +
                "     <condition attribute='status' operator='eq' value='0'/>" +
                "   </filter>" +
                " </entity>" +
                "</fetch>";
            var rettemplate = XrmServiceToolkit.Soap.Fetch(fetchXmltemplate);
            if (rettemplate && rettemplate.length > 0) {
                return rettemplate;
            }
        }
            
    }
    return null;
}




